import { defineStore } from 'pinia'
import { ref } from 'vue'
import { 
  getLanguage, 
  setLanguage as setStorageLanguage,
  getTheme,
  setTheme as setStorageTheme,
  setSidebarStatus as setStorageSidebarStatus
} from '@/utils/storage'

export const useAppStore = defineStore('app', () => {
  // 侧边栏状态
  const sidebar = ref({
    collapsed: false,
  })

  // 语言
  const language = ref(getLanguage() || 'zh-CN')

  // 主题
  const theme = ref(getTheme() || 'default')

  // 切换侧边栏折叠状态
  const toggleSidebar = () => {
    sidebar.value.collapsed = !sidebar.value.collapsed
    setStorageSidebarStatus(sidebar.value.collapsed)
  }

  // 设置语言
  const setLanguage = (lang: string) => {
    language.value = lang
    setStorageLanguage(lang)
  }

  // 设置主题
  const setTheme = (newTheme: string) => {
    theme.value = newTheme
    setStorageTheme(newTheme)
    
    // 动态加载主题样式
    loadTheme(newTheme)
  }

  // 加载主题样式
  const loadTheme = (themeName: string) => {
    // 移除之前的主题样式
    const prevTheme = document.getElementById('theme-style')
    if (prevTheme) {
      prevTheme.remove()
    }
    
    // 创建新的样式标签
    const themeLink = document.createElement('link')
    themeLink.id = 'theme-style'
    themeLink.rel = 'stylesheet'
    themeLink.href = `/themes/${themeName}.css`
    document.head.appendChild(themeLink)
    
    // 设置body的主题类名
    document.body.className = `theme-${themeName}`
    
    // 设置暗黑模式
    const isDark = themeName.includes('dark')
    document.documentElement.setAttribute('data-theme', isDark ? 'dark' : 'light')
  }

  // 初始化主题
  const initTheme = () => {
    const savedTheme = getTheme() || 'default'
    loadTheme(savedTheme)
  }

  return {
    sidebar,
    language,
    theme,
    toggleSidebar,
    setLanguage,
    setTheme,
    initTheme
  }
}) 